import { defineProps, computed, getCurrentInstance, h, defineComponent } from "vue";

export default defineComponent({
  name: "ElCol",
  props: {
    tag: {
      type: String,
      default: "div", // 确保 tag 有默认值
    },
    span: {
      type: Number,
      default: 24, //默认24等份
    },
    offset: {
      type: Number,
      default: 0,
    },
    push: {
      type: Number,
      default: 0,
    },
    pull: {
      type: Number,
      default: 0,
    },
  },

  setup(props, { slots }) {
    // 获取当前组件实例
    const vm = getCurrentInstance();
    const {
      proxy: { $parent },
    } = vm;

    // 计算 gutter 值
    const gutter = computed(() => {
      let parent = $parent;
      while (parent && parent.$options["name"] !== "ElRow") {
        parent = parent.$parent;
      }
      return parent ? parent.gutter : 0;
    });

    // 计算样式
    const style = computed(() => {
      const style = {};

      if (gutter.value) {
        style.paddingLeft = gutter.value / 2 + "px";
        style.paddingRight = gutter.value / 2 + "px";
      }
      return style;
    });

    // 计算 class 列表
    const classList = computed(() => {
      const classList = [];
      const classItem = ["span", "offset", "push", "pull"];
      classItem.forEach((item) => {
        if (props[item]) {
          classList.push(
            item === "span" ? `el-col-${props[item]}` : `el-col-${item}-${props[item]}`
          );
        }
      });
      return classList;
    });

    // 渲染函数
    return () => {
      return h(
        props["tag"],
        {
          class: ["el-col", ...classList.value],
          style: style.value,
        },
        slots.default ? slots.default() : [] // 正确访问默认插槽
      );
    };
  },
});
